package com.ktgj.service.controller;



import com.ktgj.common.core.constant.CustomerConstants;
import com.ktgj.customer.api.RemoteCustomerService;
import com.ktgj.customer.api.domain.Customer;
import com.ktgj.pay.api.RemotePayService;
import com.ktgj.pay.api.domain.WXConfigApi;
import com.ktgj.pay.api.domain.WXPayUtilApi;
import com.ktgj.service.common.JTu.JTdomain.*;
import com.ktgj.service.common.JTu.JingTu;
import com.ktgj.service.domain.*;
import com.ktgj.service.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;

@ControllerAdvice
@RestController
@RequestMapping("/callback")
public class CallbackController
{

    @Autowired
    RemoteCustomerService remoteCustomerService;
    @Autowired
    private IKtserviceOrderChannelService channelService;
    @Autowired
    private IOrderViphallService orderViphallService;
    @Autowired
    private IOrderitemViphallService orderitemViphallService;
    @Autowired
    private IOrderVipchannelService orderVipchannelService;
    @Autowired
    private IOrderitemVipchannelService orderitemVipchannelService;
    @Autowired
    private RemotePayService payService;

    /**
     * 查询并解析鲸图贵宾厅的请求数据
     * @param request
     * @return
     */
    @RequestMapping("/analyticQRCodeTCJT")
    @ResponseBody
    public KTTCJTCheckResp analyticQRCodeTCJT(@RequestBody KTCodeAnalysisValidReq request)
    {
        KTTCJTCheckResp response = new KTTCJTCheckResp();
        if (!request.channel.equals(JingTu.getInstance().getJTChannelCode()))
        {
            response.ticketNo = request.ticketNo;
            response.resCode = "-1000";
            response.resMsg = "鲸图渠道码不正确";
            return response;
        }
        try
        {
            QRCodesNewModel qrCodesNewModel = JingTu.getInstance().decryptVipHallQrCode(request.ticketNo);
            Customer customer = remoteCustomerService.getCustomerByMobile(qrCodesNewModel.Mobile);
            response.memberName = customer.getCustomerName();
            response.memberPhone = qrCodesNewModel.Mobile;
            response.ticketNo = request.ticketNo;
            response.resCode = "100";
            response.resMsg = "";
            return response;
        } catch (RuntimeException e)
        {
            response.resMsg = e.getMessage();
            response.resCode = "-1000";
            response.ticketNo = request.ticketNo;
            return response;
        }
    }


//    /**
//     * 根据解析的数据来执行鲸图贵宾厅核销记录
//     * @param request
//     * @return
//     */
//    @RequestMapping("/checkQRCodeValidTCJT")
//    @ResponseBody
//    public KTCodeValidResp checkQRCodeValidTCJT(@RequestBody KTCodeValidReq request)
//    {
//        KTCodeValidResp response = new KTCodeValidResp();
//        Random random = new Random();
//        int number = random.nextInt(9000000) + 1000000;
//        if (!request.channel.equals(JingTu.getInstance().getJTChannelCode()))
//        {
//            response.resCode = "-1000";
//            response.resMsg = "鲸图渠道码不正确";
//            response.thirdSerialId = "";
//            return response;
//        }
//        try
//        {
//            QRCodesNewModel qrCodesNewModel = JingTu.getInstance().decryptVipHallQrCode(request.ticketNo);
//            List<KtserviceOrderChannel> lstServiceOrders = channelService.selectServiceOrderByOrderId(Long.parseLong(qrCodesNewModel.Key));
//            if (lstServiceOrders.size() > 0)
//            {
//                long usedCount = lstServiceOrders.stream().mapToLong(KtserviceOrderChannel::getUsecount).sum();
//                OrderViphall viphallOrder = orderViphallService.selectOrderViphallById(Long.parseLong(qrCodesNewModel.Key));
//                if (usedCount >= viphallOrder.getPeopleNumber())
//                {
//                    response.resCode = "-1000";
//                    response.resMsg = "该订单已经超出使用数量";
//                    response.thirdSerialId = "";
//                    return response;
//                }
//            }
//            KtserviceOrderChannel orderChannel = new KtserviceOrderChannel();
//            orderChannel.setChannel(request.channel);
//            orderChannel.setTickertno(request.ticketNo);
//            orderChannel.setOrderid(Long.parseLong(qrCodesNewModel.Key));
//            orderChannel.setUsecount(Long.valueOf(request.useCount));
//            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//            Date date = dateFormat.parse(request.useTime);
//            orderChannel.setUsetime(date);
//            orderChannel.setProductuniquecode(request.productUniqueCode);
//            orderChannel.setIsself(Long.valueOf(request.isSelf));
//            orderChannel.setThridserialid("TCJT" + number);
//            orderChannel.setCreateTime(new Date());
//            channelService.insertKtserviceOrderChannel(orderChannel);
//            response.resCode = "100";
//            response.resMsg = "";
//            response.thirdSerialId = "TCJT" + number;
//            return response;
//        } catch (ParseException e)
//        {
//            response.resMsg = e.getMessage();
//            response.resCode = "-1000";
//            response.thirdSerialId = "";
//            return response;
//        }
//    }

//    /**
//     * 接收鲸图核销完成的交易流水号
//     * @param request
//     * @return
//     */
//    @RequestMapping("/usedQRCodeValidTCJT")
//    @ResponseBody
//    public KTTCJTResp usedQRCodeValidTCJT(@RequestBody KTCodeUsedReq request)
//    {
//        KTTCJTResp response = new KTTCJTResp();
//        if (!request.msgCode.equals("100")) {
//            response.resCode = "-1000";
//            response.resMsg = "核销失败";
//            return response;
//        }
//        try {
//            KtserviceOrderChannel orderChannel = new KtserviceOrderChannel();
//            orderChannel.setSerialid(request.data.serialId);
//            orderChannel.setThridserialid(request.data.thirdSerialId);
//            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//            Date date = dateFormat.parse(request.data.useTime);
//            orderChannel.setUpdateTime(date);
//            channelService.updateKtserviceOrderChannels(orderChannel);
//            response.resCode = "100";
//            response.resMsg = "核销成功";
//            return response;
//        } catch (ParseException e) {
//            response.resMsg = e.getMessage();
//            response.resCode = "-1000";
//            return response;
//        }
//    }

    /**
     * 贵宾厅微信小程序支付回调
     * @param resultMap
     * @param resultMap
     */
    @RequestMapping("/vipHallWechatPayCallback")
    public void vipHallWechatPayCallback(@RequestBody Map<String, String> resultMap) {
        boolean result = payService.isPaySuccessful(resultMap);
        String returnCode = resultMap.put("return_code", resultMap.get("return_code"));
        String resultCode = resultMap.put("result_code", resultMap.get("result_code"));
        String outTradeNo = resultMap.put("out_trade_no", resultMap.get("out_trade_no"));
        String transaction_id = resultMap.put("transaction_id", resultMap.get("transaction_id"));
        if (result) {
            if (returnCode.equals("SUCCESS") && resultCode.equals("SUCCESS")) {//交易成功
                if (outTradeNo != null) {//商户订单号
                    OrderViphall viphall = new OrderViphall();
                    viphall.setOrderNumber(outTradeNo);
                    viphall.setStatus(CustomerConstants.payd.getValue());
                    viphall.setPaymentStatus(CustomerConstants.payd.getValue());
                    viphall.setPaymentTradeserialnumber(transaction_id);
                    orderViphallService.updateByOrderNumber(viphall);

                    OrderitemViphall orderitemViphall = new OrderitemViphall();
                    orderitemViphall.setOrderviphallId(viphall.getJsjId());
                    orderitemViphall.setStatus(CustomerConstants.payd.getValue());
                    orderitemViphallService.updateByOrderViphallId(orderitemViphall);
                }
            }
        }
    }

    /**
     * VIP通道微信小程序支付回调
     * @param resultMap
     */
    @RequestMapping("/vipChannelWechatPayCallback")
    public void vipChannelWechatPayCallback(@RequestBody Map<String, String> resultMap) {
        boolean result = payService.isPaySuccessful(resultMap);
        String returnCode = resultMap.put("return_code", resultMap.get("return_code"));
        String resultCode = resultMap.put("result_code", resultMap.get("result_code"));
        String outTradeNo = resultMap.put("out_trade_no", resultMap.get("out_trade_no"));
        String transaction_id = resultMap.put("transaction_id", resultMap.get("transaction_id"));
        if (result) {
            if (returnCode.equals("SUCCESS") && resultCode.equals("SUCCESS")) {//交易成功
                if (outTradeNo != null) {//商户订单号
                    OrderVipchannel vipchannel = new OrderVipchannel();
                    vipchannel.setOrderNumber(outTradeNo);
                    vipchannel.setStatus(CustomerConstants.payd.getValue());
                    vipchannel.setPaymentStatus(CustomerConstants.payd.getValue());
                    vipchannel.setPaymentTradeserialnumber(transaction_id);
                    orderVipchannelService.updateByOrderNumber(vipchannel);

                    OrderitemVipchannel itemVipchannel = new OrderitemVipchannel();
                    itemVipchannel.setOrdervipchannelId(Long.valueOf(outTradeNo));
                    itemVipchannel.setStatus(CustomerConstants.payd.getValue());
                    orderitemVipchannelService.updateByOrdervipchannelId(itemVipchannel);
                }
            }
        }
    }
}
